﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.IO.Ports;

namespace DatalogicDragon
{
    public partial class Form1 : Form
    {
        SerialPort sp1 = new SerialPort();
        string deviceid = "";

        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            #region //配置串口
            string[] baudRate = { "300", "600", "1200", "2400", "4800", "9600", "19200", "38400", "115200" };
            foreach (string s in baudRate)
            {
                cbBaudRate.Items.Add(s);
            }

            string[] dataBit = { "5", "6", "7", "8" };
            foreach (string s in dataBit)
            {
                cbDataBits.Items.Add(s);
            }

            string[] stopBit = { "1", "1.5", "2" };
            foreach (string s in stopBit)
            {
                cbStop.Items.Add(s);
            }

            string[] parityBit = { "无", "奇校验", "偶校验" };
            foreach (string s in parityBit)
            {
                cbParity.Items.Add(s);
            }
            #endregion


            comsInit();
            //初始值
            cbBaudRate.SelectedIndex = 5;
            cbDataBits.SelectedIndex = 3;
            cbStop.SelectedIndex = 0;
            cbParity.SelectedIndex = 0;

            Control.CheckForIllegalCrossThreadCalls = false;
            sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived);
            sp1.DtrEnable = true;
            sp1.RtsEnable = true;

            tbSend.Text = "OK";
            rtbRecived.ReadOnly = true;
        }

        private void comsInit()
        {
            cbComs.Items.Clear();
            string[] coms = SerialPort.GetPortNames();
            if (coms == null)
            {
                MessageBox.Show("串口设备未连接", "错误");
            }
            else
            {
                foreach (string s in coms)
                {
                    cbComs.Items.Add(s);
                }
            }
            cbComs.SelectedIndex = 0;
        }

        void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DateTime dt = DateTime.Now;
            rtbRecived.Text += dt.ToString() + "\r\n";
            string dataRecived = sp1.ReadLine() + "\r\n";
            rtbRecived.Text += dataRecived + "\r\n";
            sp1.DiscardInBuffer();
            deviceid = dataRecived.Substring(0, 4);
            try
            {
                if (checkboxAutoBack.Checked)
                {
                    rtbRecived.Text += "writeback" + deviceid + " " + tbSend.Text + "\r\n";
                    sp1.WriteLine(deviceid + " " + tbSend.Text + "\r\n");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message, "Error");
                return;
            }
        }

        private void btnSwitch_Click(object sender, EventArgs e)
        {
            if (!sp1.IsOpen)
            {
                try
                {
                    string comName = cbComs.SelectedItem.ToString();
                    sp1.PortName = comName;

                    string strBaudRate = cbBaudRate.Text;
                    string strDateBits = cbDataBits.Text;
                    string strStopBits = cbStop.Text;
                    Int32 iBaudRate = Convert.ToInt32(strBaudRate);
                    Int32 iDateBits = Convert.ToInt32(strDateBits);

                    sp1.BaudRate = iBaudRate;       //波特率
                    sp1.DataBits = iDateBits;       //数据位
                    switch (cbStop.Text)            //停止位
                    {
                        case "1":
                            sp1.StopBits = StopBits.One;
                            break;
                        case "1.5":
                            sp1.StopBits = StopBits.OnePointFive;
                            break;
                        case "2":
                            sp1.StopBits = StopBits.Two;
                            break;
                        default:
                            MessageBox.Show("Error：参数不正确1!", "Error");
                            break;
                    }
                    switch (cbParity.Text)             //校验位
                    {
                        case "无":
                            sp1.Parity = Parity.None;
                            break;
                        case "奇校验":
                            sp1.Parity = Parity.Odd;
                            break;
                        case "偶校验":
                            sp1.Parity = Parity.Even;
                            break;
                        default:
                            MessageBox.Show("Error：参数不正确2!", "Error");
                            break;
                    }
                    //设置必要控件不可用
                    cbComs.Enabled = false;
                    cbBaudRate.Enabled = false;
                    cbDataBits.Enabled = false;
                    cbStop.Enabled = false;
                    cbParity.Enabled = false;
                    try
                    {
                        sp1.Open();     //打开串口
                    }
                    catch { }
                    btnSwitch.Text = "关闭串口";
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error:" + ex.Message, "Error");
                    return;
                }
            }
            else
            {
                sp1.Close();
                comsInit();
                btnSwitch.Text = "打开串口";
                //恢复控件功能
                //设置必要控件不可用
                cbComs.Enabled = true;
                cbBaudRate.Enabled = true;
                cbDataBits.Enabled = true;
                cbStop.Enabled = true;
                cbParity.Enabled = true;
            }
        }

        private void btnPost_Click(object sender, EventArgs e)
        {
            try
            {
                sp1.WriteLine(deviceid + tbSend.Text + "\r\n");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message, "Error");
                return;
            }
        }

        private void btnClean_Click(object sender, EventArgs e)
        {
            rtbRecived.Text = "";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            sp1.Close();
            Application.Exit();
        }
    }
}
